package cn.edu.ncu.housinghub.controller.contract;

import cn.edu.ncu.housinghub.dto.request.contract.ContractRequest;
import cn.edu.ncu.housinghub.dto.request.contract.ContractVerifyRequest;
import cn.edu.ncu.housinghub.entity.contract.Contract;
import cn.edu.ncu.housinghub.entity.contract.ContractApplication;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.service.ContractService;
import cn.edu.ncu.housinghub.service.UserService;
import cn.edu.ncu.housinghub.vo.Result;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/contract")
public class ContractController {

    @Autowired
    private ContractService contractService;

    @Autowired
    private UserService userService;

    /**
     * 租客发起签约申请
     */
    @PostMapping("/tenant/applyContract")
    public Result applyContract(@Valid @RequestBody ContractApplication application) {
        contractService.addInitContract(application);
        return Result.success();
    }

    /**
     * 房东查看签约申请列表
     */
    @GetMapping("/landlord/applications")
    public Result getLandlordApplications(@RequestHeader("info") String token) {
        User user = userService.getUserByToken(token);
        Long landlordId = user.getId(); // 假设用户ID就是房东ID，实际可能需要查询房东表
        List<Contract> applications = contractService.getContractApplications(landlordId);
        return Result.success(applications);
    }

    /**
     * 房东处理签约申请（同意/拒绝）
     */
    @PostMapping("/landlord/verify")
    public Result verifyContract(@Valid @RequestBody ContractVerifyRequest request, @RequestHeader("info") String token) {
        User user = userService.getUserByToken(token);
        request.setLandlordId(user.getId()); // 设置房东ID
        contractService.modifyContractStatus(request);
        return Result.success();
    }

    /**
     * 租客查看自己的签约申请列表
     */
    @GetMapping("/tenant/applications")
    public Result getTenantApplications(@RequestHeader("info") String token) {
        User user = userService.getUserByToken(token);
        Long tenantId = user.getId();
        List<Contract> applications = contractService.getTenantApplications(tenantId);
        return Result.success(applications);
    }

}
